/**
 * @author 云离
 * @date: 2018/12/28
 */
import React, { Component } from "react";
import { actions } from "../../../../reducers/main";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import {
  message,
  Spin,
  Table,
  Drawer,
  Button,
  Pagination,
  Modal
} from "antd";
import axios from "../../../../apis/api";
import qs from "qs";
import CardForm from "./addOrderForm";

const { confirm } = Modal;

const mapStateToProps = (state, ownProps) => {
  return {};
};

const mapDispatchToProps = dispatch => {
  return {};
};

class CardMng extends Component {
  state = {
    loading: false,
    pageSize: 10,
    curPage: 1,
    tableData: {
      total: 0,
      rows: []
    },
    initCardForm: {},
    visibleDlg: false,
    cardFormTitle: "",
    cardFormType: "add",
    selectedRowKeys: []
  };

  componentDidMount() {
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if(nextProps.data !== this.props.data && nextProps.visible) {
      this.searchTable(nextProps);
    }
  }

  searchTable = async (props= this.props) => {
    const { pageSize, curPage } = this.state;
    const query = {
      orderByColumn: "settingId",
      isAsc: "desc",
      pageSize,
      pageNum: curPage
    };
    try {
      this.setState({
        loading: true
      });
      const result = await axios.post(
        "/channel/businessPauseOrderSetting/list/" + props.data.userId,
        qs.stringify(query)
      );
      if (result.code === 0) {
        this.setState({
          tableData: result,
          loading: false,
          selectedRowKeys: []
        });
      } else {
        this.setState({
          loading: false
        });
        message.error(result.msg);
      }
    } catch (e) {
      this.setState({
        loading: false
      });
      message.error(e.message);
    }
  };
  //翻页
  handlePageChange = (page, pageSize) => {
    this.setState(
      {
        curPage: page
      },
      this.searchTable
    );
  };
  // 编辑 银行卡
  editCard = card => {
    this.setState({
      visibleDlg: true,
      cardFormType: "edit",
      initCardForm: card,
      cardFormTitle: "修改"
    });
  };
  // 删除银行卡
  delCard = card => {
    Modal.confirm({
      title: "系统提示",
      content: "确定删除该信息吗？",
      okText: "确定",
      cancelText: "取消",
      onOk: () => {
        this._batchDel({
          ids: card.settingId
        });
      },
      onCancel() {}
    });
  };
  // 添加银行卡
  addCard = () => {
    this.setState({
      visibleDlg: true,
      cardFormType: "add",
      initCardForm: {},
      cardFormTitle: "添加"
    });
  };
  batchDel = () => {
    this._batchDel({
      ids: this.state.selectedRowKeys.join(",")
    });
  };
  // 批量删除银行卡
  _batchDel = async body => {
    try {
      const result = await axios.post(
        "/channel/businessPauseOrderSetting/remove",
        qs.stringify(body)
      );
      if (result.code === 0) {
        message.success(result.msg);
      } else {
        message.error(result.msg);
      }
      this.handlePageChange(1);
    } catch (e) {
      console.log(e);
      message.error(e.message || e.msg);
    }
  };

  submitCardForm = async data => {
    if (this.state.cardFormType === "add") {
      try {
        const result = await axios.post(
          "/channel/businessPauseOrderSetting/add/"+this.props.data.userId,
          qs.stringify(data)
        );
        if (result.code === 0) {
          message.success(result.msg);
          this.cancelCardForm();
          this.handlePageChange(1);
        } else {
          message.error(result.msg);
        }
      } catch (e) {
        console.log(e);
        message.error(e.message || e.msg);
      }
    } else {
      const { initCardForm } = this.state;
      try {
        const result = await axios.post(
          "/channel/businessPauseOrderSetting/edit",
          qs.stringify({
            ...data,
            settingId: initCardForm.settingId
          })
        );
        if (result.code === 0) {
          message.success(result.msg);
          this.cancelCardForm();
          this.handlePageChange(1);
        } else {
          message.error(result.msg);
        }
      } catch (e) {
        console.log(e);
        message.error(e.message || e.msg);
      }
    }
  };

  cancelCardForm = () => {
    this.setState({
      visibleDlg: false
    });
  };

  onSelectChange = selectedRowKeys => {
    this.setState({ selectedRowKeys });
  };

  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        pageSize: pageSize,
        curPage: current
      },
      this.searchTable
    );
  };

  render() {
    const {
      loading,
      tableData,
      curPage,
      pageSize,
      selectedRowKeys
    } = this.state;
    const columns = [
      {
        title: "会员ID",
        dataIndex: "userId",
        key: "userId"
      },
      {
        title: "卡单金额",
        dataIndex: "orderPrice",
        key: "orderPrice"
      },
      {
        title: "卡第几单",
        dataIndex: "orderNum",
        key: "orderNum"
      },
      {
        title: "状态",
        dataIndex: "payStatus",
        key: "payStatus"
      },
      {
        title: "倍数",
        dataIndex: "orderTimes",
        key: "orderTimes"
      },
      {
        title: "更新时间",
        dataIndex: "updateTime",
        key: "updateTime"
      },
      ,
      {
        title: "操作",
        dataIndex: "actions",
        key: "actions",
        render: (text, record) => {
          return (
            <span>
              <Button
                size={"small"}
                type="primary"
                onClick={() => this.editCard(record)}
              >
                编辑
              </Button>
              <Button
                size={"small"}
                style={{ marginLeft: 10 }}
                type="danger"
                onClick={() => this.delCard(record)}
              >
                删除
              </Button>
            </span>
          );
        }
      }
    ];
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange
    };
    return (
      <Drawer
        title="卡单设置"
        placement="right"
        width={1000}
        closable={true}
        onClose={this.props.onClose}
        visible={this.props.visible}
      >
        <Spin spinning={loading}>
          <div style={{ marginBottom: 10 }}>
            <Button type="primary" onClick={this.addCard}>
              添加
            </Button>
            <Button
              type="danger"
              disabled={!!!selectedRowKeys.length}
              onClick={this.batchDel}
              style={{ marginLeft: 10 }}
            >
              删除
            </Button>
          </div>
          <Table
            rowSelection={rowSelection}
            dataSource={tableData.rows}
            columns={columns}
            pagination={false}
            rowKey={"bankId"}
            scroll={{ x: true }}
          />
          <Pagination
            style={{ marginTop: 10, marginBottom: 20 }}
            total={tableData.total}
            showTotal={total => `共 ${total} 项`}
            pageSizeOptions={["10", "20", "50", "100", "500"]}
            showSizeChanger
            onShowSizeChange={this.onShowSizeChange}
            pageSize={pageSize}
            current={curPage}
            onChange={this.handlePageChange}
          />
          <CardForm
            visible={this.state.visibleDlg}
            initForm={this.state.initCardForm}
            title={this.state.cardFormTitle}
            okCb={this.submitCardForm}
            cancelCb={this.cancelCardForm}
          />
        </Spin>
      </Drawer>
    );
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(CardMng));
